package com.luhuiguo.cms.server.handler;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Component;

import com.luhuiguo.cms.server.service.ChannelService;
import com.luhuiguo.cms.server.util.MapperUtils;
import com.luhuiguo.cms.shared.model.ChannelTreeModel;
import com.luhuiguo.cms.shared.rpc.LoadChannelTree;
import com.luhuiguo.cms.shared.rpc.LoadChannelTreeResult;
import com.luhuiguo.gwt.dispatcher.server.ActionHandler;
import com.luhuiguo.gwt.dispatcher.server.ExecutionContext;
import com.luhuiguo.gwt.dispatcher.shared.exception.ActionException;

@Component
public class LoadChannelTreeHandler implements ActionHandler<LoadChannelTree, LoadChannelTreeResult> {

    @Autowired
    private ChannelService channelService;


    @Override
    @PreAuthorize("isAuthenticated()")
    public LoadChannelTreeResult execute(LoadChannelTree action, ExecutionContext context) throws ActionException {

        List<ChannelTreeModel> list = MapperUtils.mapList(channelService.findChannelsByParentId(null),
                ChannelTreeModel.class);

        for (ChannelTreeModel m : list) {
            loadChidren(m);
        }
        
        return new LoadChannelTreeResult(list);

    }

    private void loadChidren(ChannelTreeModel parent) {
        
        List<ChannelTreeModel> list = MapperUtils.mapList(channelService.findChannelsByParentId(parent.getId()),
                ChannelTreeModel.class);
        
        for (ChannelTreeModel m : list) {
            parent.add(m);
            loadChidren(m);
        }
        

        //        
        // List<Channel> channels =
        // channelService.findChannelsByParent(parent.getId());
        //
        // for (Channel c : channels) {
        // ChannelTreeModel m = new ChannelTreeModel();
        //
        // m.setId(c.getId());
        // m.setName(c.getName());
        // m.setTitle(c.getTitle());
        // m.setRank(c.getRank());
        // m.setType(c.getType());
        // m.setStatus(c.getStatus());
        // parent.add(m);
        // loadChidren(m);
        //
        // }

    }

    @Override
    public Class<LoadChannelTree> getActionType() {
        return LoadChannelTree.class;
    }

    @Override
    public void rollback(LoadChannelTree action, LoadChannelTreeResult result, ExecutionContext context)
            throws ActionException {

    }

}
